package io.renren.common.utils.excel;

import cn.hutool.core.util.StrUtil;
import io.renren.common.exception.CustomException;
import io.renren.modules.impexp.controller.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description: Excel文件检查工具
 * @author: wurj
 * @Date: 2022/2/15 23:58:58
 */
@Slf4j
public class ExcelFileUtils {
    private static final String[] FILE_TYPE = {".xls", ".xlsx"};
    private static final String[] CHECK_FILE_TYPE = {".xls", ".xlsx", "xls", "xlsx"};
    private static final String FILE_REGEX = "\\.";
    public static int BATCH_SIZE = 200;
    private File file;
    private BufferedReader reader;

    /**
     * 获取文件扩展名
     *
     * @param file
     * @return
     */
    public static String getExtension(File file) {
        if (file.isDirectory()) {
            return null;
        } else {
            return "." + StringUtils.substringAfterLast(file.getName(), ".");
        }
    }

    public static ExcelFileUtils openFile(File file) {
        ExcelFileUtils kit = new ExcelFileUtils();
        kit.init(file);
        return kit;
    }

    /**
     * 校验上传Excel文件的文件格式，目前只支持.xls和.xlsx
     *
     * @param fileName
     */
    public static void checkUploadExcelType(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            log.error("导入文件名称获取失败，请更新后重新上传！");
            throw new CustomException(ResponseStatusEnum.COMMON_EXCEL_IMPORT_ERROR);
        }
        // 校验是否支持类型
        String[] strArray = fileName.split(FILE_REGEX);
        int suffixIndex = strArray.length - 1;
        String fileType = strArray[suffixIndex];

        if (!Arrays.asList(CHECK_FILE_TYPE).contains(fileType)) {
            log.error("导入文件失败:文件格式错误，只支持" + Arrays.toString(FILE_TYPE) + "文件格式");
            throw new CustomException(ResponseStatusEnum.COMMON_EXCEL_IMPORT_ERROR);
        }
    }

    private void init(File file) {
        try {
            this.file = file;
            reader = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            log.error("读取文件失败 " + file.getAbsolutePath(), e);
            throw new CustomException(ResponseStatusEnum.COMMON_EXCEL_IMPORT_ERROR);
        }
    }

    public List<String> readLines(int batchSize) {
        List<String> lines = new ArrayList<>();
        for (int i = 0; i < batchSize; i++) {
            String line;
            try {
                line = reader.readLine();
            } catch (IOException e) {
                log.error("读取文件失败 " + file.getAbsolutePath(), e);
                throw new CustomException(ResponseStatusEnum.COMMON_EXCEL_IMPORT_ERROR);
            }
            if (line != null) {
                lines.add(line);
            }
        }
        return lines;
    }

    public void close() {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("关闭文件失败 " + file.getAbsolutePath(), e);
            throw new CustomException(ResponseStatusEnum.COMMON_EXCEL_IMPORT_ERROR);
        }
    }

}
